const context  = require.context('../pages', true, /\.js$/)

/* pages下带有js文件的路径集合 */
const paths = context.keys()

/* 去除Eror路由 */
// const dealPaths = paths.filter( path => path.indexOf('Error') < 0 )

/* 处理成路由使用的对象 */
const initialRoutes = paths.map( path => {

  /* 文件内的组件 */
  const component = context(path).default

  /* 可使用的路由路径 */
  const replacePath = path.substring(1).replace(/(\/index\.js|\.js)$/,'').toLowerCase()
  
  /* 是否需要登录访问的设置 */
  const auth = component.auth || false

  /* 是否需要精准匹配 */
  const exact = component.exact || false
  /* 路由描述 */
  const meta = component.meta || {}

  return {
    component,
    path: replacePath,
    auth,
    exact,
    meta
  }
})


/* 生成路由的id和父路由id */
const routesHasId = initialRoutes.map( route => {
  const newRoute = {}
  /* 将路径拆分成单词集合 */

  const mergePath = route.path.slice(1).split('/')

  /* 如果只有一个单词就没有父路由 */
  if (mergePath.length === 1) {
    newRoute.id = mergePath.join()
  } 

  /* 大于一个则包含父路由，设置parentId */
  else {
    newRoute.id = mergePath.join('-') 
    newRoute.parentId = mergePath.slice(0, mergePath.length - 1).join('-')
  }

  return { ...newRoute, ...route}
} )

/* 合并路由子路由到父路由的children中 */
const fullRoutes = []
const pureRoutesHasId = Array.from(routesHasId)

/* 第一次循环取出每一个路由并判断是否有parentId */
for (let oneIndex = 0, oneLength = pureRoutesHasId.length; oneIndex < oneLength; oneIndex++) {
  const oneRoute = pureRoutesHasId[oneIndex]

  if (oneRoute.parentId) {

    /* 第二次循环是判断该次的路由parentId如果和第一次循环的路由id对应则属于此路由的子路由 */
    for (let twoIndex = 0, twoLength = pureRoutesHasId.length; twoIndex < twoLength; twoIndex++) {
      const twoRoute = pureRoutesHasId[twoIndex]

      if ( oneRoute.parentId === twoRoute.id ) {

        /* 如果有children则追加元素，没有则添加新的数组 */
        twoRoute.children = twoRoute.children ? [...twoRoute.children, oneRoute] : [oneRoute]

      }

    }

  } 

  /* 进入此分支的是父级路由 */
  else {
    fullRoutes.push(oneRoute)
  }

}

export const filtRoutes = routesHasId
export default fullRoutes